<template>
  <div class="user-settings">
    <h3>修改个人资料</h3>
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        class="settings-form"
    >
      <el-form-item label="头像" prop="userAvatar">
        <div class="avatar-upload-area">
          <el-avatar :size="80" :src="form.userAvatar || defaultAvatar" class="avatar-preview" />

          <el-upload
              class="upload-button"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatarFile"
          >
            <el-button size="small" type="primary" text>上传/更换</el-button>
          </el-upload>
        </div>
        <div class="tip">仅支持 JPG/PNG 格式，大小不超过 2MB。</div>
      </el-form-item>

      <el-form-item label="昵称" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入昵称" />
      </el-form-item>

      <el-form-item label="简介" prop="userProfile">
        <el-input
            v-model="form.userProfile"
            type="textarea"
            :rows="4"
            placeholder="请输入你的个人简介"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ loading ? '保存中...' : '保存修改' }}
        </el-button>
        <el-button @click="emit('cancelEdit')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import type { FormInstance, FormRules, UploadProps, UploadRawFile } from 'element-plus';
import { ElMessage } from 'element-plus';
import {FileControllerService, UserControllerService, type UserUpdateMyRequest, type UserVO} from "../../../generated";

const props = defineProps<{
  initialData: UserVO;
}>();

// ⭐️ 新增 'cancelEdit' 事件
const emit = defineEmits(['updateSuccess', 'cancelEdit']);

const formRef = ref<FormInstance>();
const loading = ref(false);
const defaultAvatar = 'http://t3jtjn58z.hd-bkt.clouddn.com/OIP.jpg';
// ⭐️ 新增状态：存储待上传的原始文件
const rawAvatarFile = ref<UploadRawFile | null>(null);

const form = reactive<UserUpdateMyRequest>({
  userName: '',
  userAvatar: '', // 当前显示的头像URL (可以是本地预览URL，也可以是后端URL)
  userProfile: '',
});

watch(() => props.initialData, (newVal) => {
  if (newVal) {
    form.userName = newVal.userName || '';
    form.userAvatar = newVal.userAvatar || '';
    form.userProfile = newVal.userProfile || '';
  }
}, { immediate: true });

// 表单验证规则
const rules: FormRules = {
  userName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
};

// --------------------- 头像上传逻辑 ---------------------

// 文件格式和大小校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isTypeValid = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isTypeValid) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
  }
  return isTypeValid && isLt2M;
};

// 文件选择/改变事件 (用于本地预览)
const handleAvatarChange: UploadProps['onChange'] = (uploadFile) => {
  if (beforeAvatarUpload(uploadFile.raw as UploadRawFile)) {
    rawAvatarFile.value = uploadFile.raw as UploadRawFile;
    // 创建本地 URL 用于预览
    form.userAvatar = URL.createObjectURL(uploadFile.raw as UploadRawFile);
  } else {
    // 校验失败，重置文件
    rawAvatarFile.value = null;
  }
};

// 文件上传到服务器的请求
const uploadAvatarFile = async (file: UploadRawFile): Promise<string | undefined> => {

  // 1. 创建一个 FormData 实例
  const formData = new FormData();

  // 2. 将文件和其它参数附加到 FormData 对象中
  //    第一个参数 'file' 是 key，必须和后端 Spring 控制器 @RequestPart("file") 注解中的值一致
  formData.append('file', file as any);
  //    同样，'biz' 这个 key 也必须和后端接收该参数的 @RequestPart("biz") 一致
  formData.append('biz', 'user_avatar');

  try {
    // 3. 使用 FormData 对象调用修改后的上传服务
    const res = await FileControllerService.uploadFile(formData);

    if (res.code === 0) {
      return res.data; // 返回服务器上的图片 URL
    } else {
      ElMessage.error(res.message);
      return undefined; // 或者进行其他错误处理
    }
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("文件上传失败");
    return undefined;
  }
}

// --------------------- 提交逻辑 ---------------------

const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      let finalAvatarUrl = form.userAvatar;

      try {
        // 1. 如果选择了新文件，先上传文件，并获取 URL
        if (rawAvatarFile.value) {
          finalAvatarUrl = await uploadAvatarFile(rawAvatarFile.value);
          rawAvatarFile.value = null; // 上传成功后清空
        }

        // 2. 构造最终请求体
        const request: UserUpdateMyRequest = {
          userName: form.userName,
          userProfile: form.userProfile,
          userAvatar: finalAvatarUrl, // 使用最新的 URL
        };

        // 3. 后端调用逻辑
        const res = await UserControllerService.updateMyUser(request);
        if(res.code === 0) {
          if (rawAvatarFile.value) {
            rawAvatarFile.value = null;
          }
          // 4. 通知父组件更新成功
          emit('updateSuccess', request);
        } else {
          // 业务失败：后端返回了 res 对象，但业务码或数据表示失败
          throw new Error(res.message || '资料更新失败，请重试');
        }

      } catch (error) {
        const errorMessage = (error as Error).message || '网络连接失败，请检查或稍后重试。';
        ElMessage.error(errorMessage);
        console.error('更新个人资料失败:', error);
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.user-settings {
  padding: 20px;
}

h3 {
  margin-bottom: 25px;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.settings-form {
  max-width: 600px;
}

.avatar-upload-area {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  border: 1px solid #ddd;
}

.upload-button {
  display: inline-block;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>